﻿using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using System.IO;
using System.Text;
using System.Configuration;

using VietPublisher.FileManager;
using VietPublisher.BaseProject.Utils.Miscellaneous;
using VietPublisher.BaseProject.Utils.ImageUtils;
using System.Drawing;


namespace VietPublisher.Web.Framework
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    //[WebService(Namespace = "http://tempuri.org/")]
    //[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class ImageHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            HttpResponse response = context.Response;

            ConfigurationManager.AppSettings[DConst.absolutePath] = context.Request.PhysicalApplicationPath;

            // Image of User
            string empCode = context.Request.Params["empcode"] ?? string.Empty;
            string fileId = context.Request.Params["FileId"] ?? string.Empty;
            string groupId = context.Request.Params["GroupId"] ?? string.Empty;

            try
            {
                if (!string.IsNullOrEmpty(empCode))
                {
                    // load user picture
                    FileUtility instance = new FileUtility(false);

                    string folder = instance.GetLocation(DConst.hrDataLocationKey) + "\\EmpPicture";
                    string filePath = Path.Combine(folder, empCode + ".jpg");
                    string defFilePath = context.Server.MapPath(context.Request.ApplicationPath + "Content/image/default/shared/default_pic.jpg");
                    WriteRemoteFile(response, filePath, defFilePath);
                }
                else if (!string.IsNullOrEmpty(fileId))
                {
                    Guid FileId = new Guid(fileId);
                    WriteImage(response, FileId);

                }
                else if (!string.IsNullOrEmpty(groupId))
                {
                    int nGroupId = int.Parse(groupId);
                    WriteGroupFiles(response, nGroupId);
                }
            }
            catch (Exception ex)
            {
                LogUtility.LogMessage("", "", ex.Message + " " + ex.StackTrace);
                response.Clear();
            }
            finally
            {
                response.End();
            }
        }

        public void WriteImage(HttpResponse response, Guid fileId)
        {
            FileUtility instance = new FileUtility();
            var file = instance.GetFileInfo(fileId);
            if (file != null)
            {
                WriteRemoteFile(response, file.PhysicalPath, string.Empty);
            }
        }

        public void WriteRemoteFile(HttpResponse response, string filePath, string defaultFilePath)
        {
            byte[] data;
            FileUtility instance = new FileUtility(true);
            bool exists = instance.DownloadFile(filePath, out data);

            string fileName = Path.GetFileName(filePath);
            //response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";");

            if (exists)
            {
                //LogUtility.LogMessage(filePath);                    

                response.ContentType = GetContentTypeByFileType(Path.GetExtension(filePath).Substring(1));
                response.BinaryWrite(data);
            }
            else
            {
                //LogUtility.LogMessage(defaultFilePath);

                response.ContentType = GetContentTypeByFileType(Path.GetExtension(defaultFilePath).Substring(1));
                response.WriteFile(defaultFilePath);
            }
        }

        public void WriteGroupFiles(HttpResponse response, int groupId)
        {

            byte[] data;
            FileUtility instance = new FileUtility(true);
            string fileName = instance.DownloadFile(groupId, out data);
            response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";");
            response.ContentType = "application/zip";
            response.BinaryWrite(data);
        }

        private string GetContentTypeByFileType(string fileType)
        {
            return "application/" + fileType;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// write image to tmp folder
        /// when save is move to real folder and resize pic
        /// </summary>
        /// <param name="Buffer"></param>
        /// <param name="extFile">ext of file ex: .JPG .GIF v.v</param>
        public int WriteToFile(byte[] Buffer, string NameFile)
        {
            int GroupIdReturn = 0;
            try
            {
                #region step 1: write file to hard disk on server
                // Create a file
                Guid fileId = Guid.NewGuid();
                string extFile = NameFile.Substring(NameFile.IndexOf('.'));
                string fileName = fileId.ToString() + extFile;

                string strPath = ConfigurationManager.AppSettings[DConst.absolutePath] + ConfigurationManager.AppSettings[DConst.realImagePath] + fileName;
                FileStream newFile = new FileStream(strPath, FileMode.Create);

                // Write data to the file

                newFile.Write(Buffer, 0, Buffer.Length);

                // Close file

                newFile.Close();
                #endregion
                #region step 2: resize image
                ImageResize image = new ImageResize();
                Image tempImage = null;
                using (FileStream fs = new FileStream(strPath, FileMode.Open, FileAccess.Read))
                {
                    tempImage = Image.FromStream(fs);
                }
                int height= int.Parse(ConfigurationManager.AppSettings[DConst.realImageHeight]);
                int width=int.Parse(ConfigurationManager.AppSettings[DConst.realImageWidth]);
                var imageReturn = image.resizeImage(tempImage, new Size(height, width));

                //step 2a.
                MemoryStream ms = new MemoryStream();
                switch (extFile.ToLower())
                {
                    case ".jpg":
                        {
                            imageReturn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                            break;
                        }
                    case ".jpeg":
                        {
                            imageReturn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                            break;
                        }
                    case ".bmp":
                        {
                            imageReturn.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
                            break;
                        }
                    case ".png":
                        {
                            imageReturn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                            break;
                        }
                }

                var buf = ms.ToArray();


                FileStream ReplaceFile = new FileStream(strPath, FileMode.Create);
                ReplaceFile.Write(buf, 0, buf.Length);
                ReplaceFile.Close();

                #endregion

                #region step 3: write to dababase
                VietPublisherEntities_FileManager fileManager = new VietPublisherEntities_FileManager();
                T_SC_FileGroup fileGroup = new T_SC_FileGroup()
                {
                    Name = "Image Book",
                };
                fileManager.T_SC_FileGroup.AddObject(fileGroup);
                fileManager.SaveChanges();

                GroupIdReturn = fileGroup.GroupId;

                T_SC_FileList fileUpload = new T_SC_FileList()
                {
                    Ext = extFile,
                    FileId = fileId,
                    Name = NameFile,
                    PhysicalPath = ConfigurationManager.AppSettings[DConst.realImagePath] + fileName,
                    GroupId = fileGroup.GroupId,
                    T_SC_FileGroup = fileGroup
                };
                fileManager.T_SC_FileList.AddObject(fileUpload);
                fileManager.SaveChanges();
                #endregion
            }
            catch (Exception e)
            {
                return 0;
            }
            return GroupIdReturn;

        }
    }

}
